const fs = require('fs');
const path = require('path');
const lodash = require('lodash');
const { getMatchRowNumber, insertInLineNo, eslintFormat } = require('./utils');

const insertRoutesString = (jsx, importPath, componentName) => {
  // 找export default变量名
  const { hooks } = global.config;
  const [_, variableString] = jsx.split('export default');
  const [variable] = variableString.trim().split(';');
  // 根据变量名找到路由数组
  try {
    const [rowNumber] = getMatchRowNumber(`const ${variable}`, importPath);
    let str;
    const obj = {
      path: `/${lodash.camelCase(componentName)}`,
      key: `/${lodash.camelCase(componentName)}`,
      name: `${lodash.camelCase(componentName)}`,
      component: componentName,
      exact: true,
    };
    const handleObj =
      hooks && hooks.beforeInsertRoute ? hooks.beforeInsertRoute(obj) : obj;
    str = '{';
    Object.entries(handleObj).forEach(([key, value]) => {
      str += `${key}:${
        typeof value !== 'string' || key === 'component' ? value : `'${value}'`
      },`;
    });
    str += '},';
    const aftertrans = str.replace(/\n/g, '\\n');
    insertInLineNo(Number(rowNumber) + 1, aftertrans, importPath);
  } catch (e) {
    console.log(e);
  }
};

const insertPath = (componentName) => {
  const { routesPath, basePath } = global.config;
  if (!routesPath) return;
  const myBasePath = path.join(global.cwdPath, basePath);
  const importsPath = path.join(global.cwdPath, routesPath);
  if (fs.existsSync(importsPath)) {
    const relativePath = path
      .relative(path.join(importsPath, '../'), myBasePath)
      .replace(/\\/g, '/');
    const file = fs.readFileSync(importsPath, {
      encoding: 'utf-8',
    });
    insertRoutesString(file, importsPath, componentName);
    const lazyRows = getMatchRowNumber('React.lazy', importsPath);
    if (lazyRows.length > 1) {
      // >1证明找到了为懒加载模式的代码
      const finalRow = lazyRows[lazyRows.length - 2];
      const str = `const ${componentName} = React.lazy(() => import('./${relativePath}/${componentName}'));`;
      insertInLineNo(Number(finalRow) + 1, str, importsPath);
    } else {
      const str = `import ${componentName} from './${relativePath}/${componentName}'`;
      insertInLineNo(1, str, importsPath);
    }
    eslintFormat(importsPath);
  }
};
module.exports = insertPath;
